<template>
  <div class="reservationwrap" v-show="this.$store.state.isShowReservation">
    <div class="title">
      <span>服务预约</span>
      <van-icon @click="locate" name="location" size="40" />
    </div>
    <div id="mapid" class="map"></div>
    <!-- //信息统计板块 -->
    <div class="infopanel">
      <van-field center v-model="curlocation" label="当前位置" />
      <van-field center v-model="address" label="地址" />
      <van-field center v-model="servicecontent" label="服务内容" />
      <van-field
        v-model="resdate"
        readonly
        clickable
        center
        name="calendar"
        label="日历"
        placeholder="点击选择日期"
        @click="showCalendar = true"
      />
      <van-popup
        v-model="showCalendar"
        safe-area-inset-bottom
        position="bottom"
      >
        <van-datetime-picker
          v-model="currentDate"
          type="datetime"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onConfirm"
        />
      </van-popup>

      <van-field center v-model="telnum" label="联系电话" />
      <van-button round type="primary" class="btnsubmit" @click="submitInfo"
        >提交预约</van-button
      >
    </div>
  </div>
</template>
<script>
import * as SERVICE from '../utils/service'
import gcoord from 'gcoord'
import Map from 'ol/Map'
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'
import OSM from 'ol/source/OSM'
import View from 'ol/View'
import { defaults } from 'ol/control.js'
import { fromLonLat } from 'ol/proj'
import XYZ from 'ol/source/XYZ'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import VectorSource from 'ol/source/Vector'
import { Icon, Text, Stroke, Fill, Style } from 'ol/style'
import { Notify } from 'vant'
export default {
  data() {
    return {
      currentDate: new Date(),
      map: undefined,
      layers: undefined,
      lnglat: {
        lng: undefined,
        lat: undefined,
      },
      curlocation: '',
      address: '',
      servicecontent: '',
      resdate: '',
      telnum: '',
      showCalendar: false, //是否显示日期选择器
      maxDate: new Date(new Date().getTime() + 31 * 24 * 3600 * 1000),
      minDate: new Date('2018-01-01'),
    }
  },
  computed: {
    onShowReservationState() {
      return this.$store.state.isShowReservation
    },
  },
  watch: {
    onShowReservationState(value) {
      if (value) {
        this.initComponent()
      }
    },
  },
  mounted() {
    this.$nextTick(() => {
      // this.initComponent()
    })
  },
  methods: {
    initComponent() {
      let _this = this
      //获取位置信息
      navigator.geolocation.getCurrentPosition(
        (position) => {
          let coords = position.coords
          _this.$data.lnglat.lng = coords.longitude
          _this.$data.lnglat.lat = coords.latitude
          //初始化属性
          _this.$data.curlocation =
            '(' + coords.longitude + ',' + coords.latitude + ')'
          SERVICE.geocoordBylonlat(coords.longitude, coords.latitude).then(
            (res) => {
              _this.address = res.data
            }
          )
          //自动获取联系电话
          _this.telnum = JSON.parse(localStorage.getItem('userinfo')).phoneNum
          //初始化地图
          if (!this.map) {
            this.$data.map = new Map({
              layers: [
                //定义图层
                new TileLayer({
                  source: new XYZ({
                    url:
                      'http://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                    wrapX: true,
                  }),
                }),
              ],
              target: 'mapid',
              view: new View({
                center: fromLonLat(
                  gcoord.transform(
                    [this.lnglat.lng, this.lnglat.lat],
                    gcoord.WGS1984,
                    gcoord.GCJ02
                  )
                ),
                zoom: 17,
                projection: 'EPSG:3857',
              }),
              controls: new defaults({
                attribution: false,
                rotate: false,
                zoom: false,
              }),
            })
          }
          this.map
            .getView()
            .setCenter(
              fromLonLat(
                gcoord.transform(
                  [this.lnglat.lng, this.lnglat.lat],
                  gcoord.WGS1984,
                  gcoord.GCJ02
                )
              )
            )
          _this.createIcon(
            gcoord.transform(
              [coords.longitude, coords.latitude],
              gcoord.WGS1984,
              gcoord.GCJ02
            )
          )
          // _this.createIcon([coords.longitude, coords.latitude])
        },
        (error) => {
          console.log(error)
        }
      )
    },
    /**定位图标 */
    locate() {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          let lon = position.coords.longitude,
            lat = position.coords.latitude
          this.$data.curlocation =
            '(' +
            position.coords.longitude +
            ',' +
            position.coords.latitude +
            ')'
          console.log(lon, lat)
          this.map.getView().setZoom(17)
          this.map.getView().setCenter(
            fromLonLat(
              // gcoord.transform(lnglat, gcoord.WGS1984, gcoord.GCJ02)
              [lon, lat]
            )
          )
          this.createIcon([lon, lat])
        },
        (error) => {
          console.log(error)
        }
      )
    },
    /**创建定位图标 */
    createIcon(_lnglat) {
      var iconFeature = new Feature({
        geometry: new Point(
          fromLonLat(_lnglat)
          // fromLonLat(gcoord.transform(_lnglat, gcoord.WGS84, gcoord.GCJ02))
        ),
        name: 'Null Island',
      })

      var iconStyle = new Style({
        image: new Icon({
          anchor: [0.5, 0.5],
          // anchorXUnits: 'fraction',
          // anchorYUnits: 'pixels',
          crossOrigin: 'anonymous',
          src: require('../../static/imgs/locationmarker.png'),
          // imgSize: [12, 12],
          // opacity: 0.5,//透明度
          scale: 0.3,
        }),
      })

      iconFeature.setStyle(iconStyle)

      var vectorSource = new VectorSource({
        features: [iconFeature],
      })

      var vectorLayer = new VectorLayer({
        source: vectorSource,
        visible: true,
      })
      if (this.layers) this.map.removeLayer(this.layers)
      this.layers = vectorLayer
      this.map.addLayer(vectorLayer)
    },
    /**
     * 确定日期选择
     */
    onConfirm(value) {
      console.log(value)
      this.showCalendar = false //关闭遮罩
      this.resdate = this.$moment(value.getTime()).format('yy-MM-DD HH:mm:ss') //格式化时间：yy-MM-DD HH:mm:ss
    },
    /**提交预约信息 */
    submitInfo() {
      //将数据发送到数据库中，进行存储
      //验证数据是否填写完整
      if (!this.servicecontent || !this.resdate) {
        Notify({ type: 'danger', message: '信息未填写完整！' })
        return false
      }
      //上报信息
      SERVICE.insertServiceOrder(
        this.telnum,
        this.servicecontent,
        this.address,
        this.lnglat.lng,
        this.lnglat.lat
      ).then((res) => {
        if (res.data != 0) {
          Notify({ type: 'success', message: '预约信息已提交,请稍后！' })
          //清空当前数据
          this.servicecontent = ''
          this.resdate = ''
        } else Notify({ type: 'danger', message: '预约信息提交失败,请重试！' })
      })
    },
  },
}
</script>
<style lang="less" scoped>
.reservationwrap {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  font-size: 0.4rem;
  background-image: url('../../static/imgs/reservation/bk.jpg');
  z-index: 6;
  // 预约服务标题
  .title {
    display: flex;
    justify-content: space-between;
    font-size: 0.5rem;
    text-align: left;
    padding: 15px;
    color: orangered;
    font-weight: 700;
    border-bottom: 1px solid skyblue;
  }
  //地图
  .map {
    height: 45%;
    // background-color: rgb(204, 189, 184);
    border-bottom: 1px solid skyblue;
  }
  // 信息统计板块
  .infopanel {
    background-color: snow;
    height: 40%;
    .btnsubmit {
      // margin-top: 0.5rem;
    }
  }
}
</style>
